<template>
  <AppNavBar> 用户登录 </AppNavBar>
  <div class="logo">
    <img src="../../assets/images/logo.png" alt="" />
  </div>
  <Form @submit="onSubmit">
    <cell-group inset>
      <field
        v-model="userInfo.email"
        name="邮箱"
        label="邮箱地址"
        placeholder="邮箱地址"
        :rules="[{ required: true, message: '请填写邮箱地址' }]"
      />
      <field
        v-model="userInfo.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </cell-group>
    <div style="margin: 16px">
      <Button round block color="#42b983" native-type="submit">登录</Button>
      <router-link to="/register">没有账号？马上去注册</router-link>
    </div>
  </Form>
</template>

<script>
import { reactive } from 'vue'
import { login } from '@/api/user'
import AppNavBar from '@/components/library/AppNavBar.vue'
import { Form, Field, CellGroup, Button, Toast } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
export default {
  name: 'Register',
  components: { Form, Field, CellGroup, Button, AppNavBar },
  setup () {
    const userInfo = reactive({
      email: null,
      password: null
    })
    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    const onSubmit = () => {
      // 点击默认会校验
      login(userInfo).then(res => {
        // 登陆成功后跳转至之前的页面
        if (res.status === 200) {
          Toast.success('登录成功')
          // 存储token到本地
          window.localStorage.setItem('token', res.data.access_token)
          // 设置用户和数量
          store.commit('setUser', { isLogin: true })
          store.dispatch('updateCartCount')
          setTimeout(() => {
            if (route.query.from) {
              router.push(route.query.from)
            } else {
              router.back()
            }
          })
        } else {
          Toast.fail('登录失败，' + res.data.errors.email[0])
        }
      })
    }
    return {
      onSubmit,
      userInfo
    }
  }
}
</script>

<style scoped lang='less'>
.logo {
  text-align: center;
  img {
    margin-top: 83px;
    margin-bottom: 30px;
    width: 50vw;
  }
}
a {
  display: block;
  text-align: right;
  margin-top: 15px;
  color: #ddd;
  font-size: 12px;
}
</style>
